import re
import urllib

class AppURLopener(urllib.FancyURLopener):
	version = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.12) Gecko/20050915 Firefox/1.0.7"

class module:
	def __init__(self, parent):
		self.parent = parent
		self.events = ["onPrivmsg"]
		self.metadata = {
        "name":"Google",
        "description":"Google Search Module",
        "author":"Samuel Gordalina",
        "email":"samuel.gordalina@gmail.com",
        "version":"0.1",
        "required_version":(0,1)
		}

		urllib._urlopener = AppURLopener()

	def onPrivmsg(self, mask, message, channel=""):
		if channel=="" or message.split(" ")[0].lower() != "!google" or message.split(" ")[1] == "":
			return False
	
		search = urllib.urlopen("http://www.google.com/search?q=" + urllib.quote_plus(message[7:])).read()
		result = re.search('class=l href="(.*?)">(.*?)</a.*?j><font.*?>(.*?)<br><', search, re.DOTALL)
		google = re.sub('<.*?>', '', (result.group(1) + '\n' + result.group(2) + '\n' + result.group(3)))

		google = google.split("\n")
		# google[0] == URL
		# google[1] == Title
		# google[2] == Description

		self.parent.irc.privmsg(channel, '"' + google[0] + '"')
